package plus.easydo.server.oauth.service;

import cn.hutool.core.bean.BeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import plus.easydo.api.UserServiceFeignClient;
import plus.easydo.api.model.SysRole;
import plus.easydo.api.model.SysUser;
import plus.easydo.core.exception.CustomException;
import plus.easydo.core.result.R;
import plus.easydo.starter.log.annotation.SystemLog;
import plus.easydo.starter.oauth.core.model.CustomizeUserDetails;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 自定义账户密码验证服务
 * @author yuzhanfeng
 */
@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {

    protected final Logger log = LoggerFactory.getLogger(MyUserDetailsServiceImpl.class);

    @Autowired
    UserServiceFeignClient userService;


    private static final String FABLED_STATUS = "1";

    @SystemLog(value = "登录",saveLog = true)
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = null;
        try {
            R<SysUser> r = userService.findByUserName(username);
            sysUser = r.getData();
        }catch (CustomException e) {
            throw new UsernameNotFoundException(e.getMessage());
        }
        if (sysUser == null){
            throw new UsernameNotFoundException("账户不存在，或已删除");
        }
        if (FABLED_STATUS.equals(sysUser.getStatus())){
            throw new UsernameNotFoundException("账户已锁定");
        }
        if (FABLED_STATUS.equals(sysUser.getDelFlag())){
            throw new UsernameNotFoundException("账户已删除");
        }
        List<SimpleGrantedAuthority> roles = new ArrayList<>();
        Set<String> perms = sysUser.getPermissions();

        List<SysRole> rolesList = sysUser.getRoles();
        if (rolesList != null && !rolesList.isEmpty()) {
            roles = rolesList.stream().map(role -> new SimpleGrantedAuthority(role.getRoleKey())).collect(Collectors.toList());
        }
        Map<String,Object> userMap =  BeanUtil.beanToMap(sysUser);
        userMap.put("id",sysUser.getUserId());
        userMap.put("username",sysUser.getUserName());
        userMap.put("password",sysUser.getPassword());
        userMap.remove("rolesList");
        userMap.remove("menuList");
        return new CustomizeUserDetails<Long>(userMap,roles,perms);
    }
}
